/* eslint-disable react-hooks/exhaustive-deps */
/*
 * @Author: zy
 * @Date: 2021-10-21 09:30:21
 * @Last Modified by:   lt
 * @Last Modified time: 2021-10-27 15:37:14
 */

import React, { useState, useEffect } from 'react';
import { Modal, Button, Space, Form, Input, TreeSelect, message } from 'antd';
import { checkFatherClassification, saveClassification } from '@/services/classification';
import type {
  OptionClassificationInfoDataType,
  ClassificationItem,
  TreeDataType,
} from '@/services/classification';

type PropsType = {
  modalVisible: boolean;
  hideModal: () => void;
  dataSource: OptionClassificationInfoDataType | undefined;
  modifyAid: number;
  treeData: ClassificationItem[] | [];
};

const ClassificationManageModal = ({
  modalVisible,
  hideModal,
  dataSource,
  modifyAid,
  treeData,
}: PropsType) => {
  const [form] = Form.useForm(); // 表单对象
  const [modalTitle, setModalTitle] = useState('新增'); //设置modal标题
  const [isDisabled, setIsDisabled] = useState(false); //设置提交按钮是否可用
  const [loading, setLoading] = useState(false); //设置确认按钮的loading
  const Layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };

  /**
   * @description: 表单初始化(1、渲染modal数据；2、判断modal标题)
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      if (dataSource) {
        const { name, fatherName, fatherAid } = dataSource.data;
        form.setFieldsValue({ name, fatherType: { label: fatherName, value: fatherAid } });
      } else {
        form.resetFields();
      }
      setModalTitle(modifyAid === -1 ? '新增' : '修改');
    }
    return function cleanup() {
      mounted = false;
    };
  }, [modifyAid]);

  /**
   * @description: 设置树形结构数据(将传入的treedata转换成树形结构的数据)
   */
  const handleData = (data: ClassificationItem[] | []) => {
    const item: TreeDataType[] = [];
    data.map((list) => {
      const newData: TreeDataType = {
        value: 0,
        title: '',
        children: [],
      };
      newData.value = list.aid;
      newData.title = list.name;
      newData.children = list.children ? handleData(list.children) : []; // 如果还有子集，就再次调用自己
      item.push(newData);
    });
    return item;
  };

  /**
   * @description: 校验父类(传入的值，调用接口进行校验并做提示)
   */
  const checkLogic = async (node: any) => {
    if (node) {
      const { value, label } = node;
      if (modifyAid !== -1) {
        const params = { aid: modifyAid, fatherAid: value };
        const msg = await checkFatherClassification(params);
        if (msg?.code === 10000) {
          if (msg.data.isDescendant) {
            setIsDisabled(true);
            message.error(`${label}不可作为该类型的父级类型，请进行修改`);
          } else {
            setIsDisabled(false);
          }
        } else {
          setIsDisabled(true);
          message.error(msg ? msg.message : '校验失败');
        }
      }
    } else {
      setIsDisabled(false);
    }
  };

  /**
   * @description: 表单提交(传入的值，调用接口保存表单数据并做提示)
   */
  const finishHandler = async (value: any) => {
    setLoading(true);
    const { name, fatherType } = value;
    let params;
    if (fatherType) {
      params = { aid: modifyAid, name, fatherAid: fatherType.value };
    } else {
      params = { aid: modifyAid, name };
    }
    const msg = await saveClassification(params);
    if (msg?.code === 10000) {
      setTimeout(() => {
        message.success('提交成功');
        hideModal();
      }, 200);
    } else {
      message.error(msg ? msg.message : '提交失败');
    }
    setLoading(false);
  };

  return (
    <div>
      <Modal
        forceRender
        getContainer={false}
        width={649}
        title={modalTitle}
        visible={modalVisible}
        onCancel={hideModal}
        footer={
          <Space>
            <Button onClick={hideModal}>取消</Button>
            <Button
              type="primary"
              disabled={isDisabled}
              loading={loading}
              onClick={() => form.submit()}
            >
              确定
            </Button>
          </Space>
        }
      >
        <Form {...Layout} layout="horizontal" form={form} onFinish={finishHandler}>
          <Form.Item
            name="name"
            label="名称："
            validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入类型名称' },
              { max: 16, type: 'string', message: '类型名称最长为16个字符' },
            ]}
          >
            <Input placeholder="请输入" allowClear={true} />
          </Form.Item>
          <Form.Item name="fatherType" label="父级类型：">
            <TreeSelect
              placeholder="请选择"
              allowClear
              treeData={handleData(treeData)}
              onChange={(value) => checkLogic(value)}
              labelInValue={true}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ClassificationManageModal;
